package com.yuuzy.service.impl;

import com.yuuzy.constant.MessageConstant;
import com.yuuzy.dto.PasswordEditDTO;
import com.yuuzy.dto.UserDTO;
import com.yuuzy.dto.UserLoginDTO;
import com.yuuzy.entity.User;
import com.yuuzy.exception.AccountNotFoundException;
import com.yuuzy.exception.PasswordErrorException;
import com.yuuzy.mapper.UserMapper;
import com.yuuzy.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserMapper userMapper;

	/**
	 * 用户登录
	 *
	 * @param userLoginDTO
	 * @return user
	 */
	public User login(UserLoginDTO userLoginDTO) {
		String username = userLoginDTO.getUsername();
		String password = userLoginDTO.getPassword();

		//1、根据用户名查询数据库中的数据
		User user = userMapper.getByUsername(username);

		//2、处理各种异常情况（用户名不存在、密码不对）
		if (user == null) {
			//账号不存在
			throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
		}

		//密码比对
		//进行md5加密，然后再进行对比
		password = DigestUtils.md5DigestAsHex(password.getBytes());
		if (!password.equals(user.getPassword())) {
			//密码错误
			throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
		}
		

		//3、返回实体对象
		return user;
	}

	/**
	 * 用户注册
	 * @param userDTO
	 */
	@Override
	public void register(UserDTO userDTO) {
		User user = new User();
		//对象属性拷贝
		BeanUtils.copyProperties(userDTO, user);

		//将密码进行md5加密
		user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));

		userMapper.insert(user);

	}

	/**
	 * 修改密码
	 * @param passwordEditDTO
	 */
	@Override
	public void editPassword(PasswordEditDTO passwordEditDTO) {
		String username = passwordEditDTO.getUsername();
		String newPassword = passwordEditDTO.getNewPassword();

		User user = userMapper.getByUsername(username);

		//处理异常
		if (user == null) {
			//账号不存在
			throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
		}

		//修改密码
		user.setPassword(DigestUtils.md5DigestAsHex(newPassword.getBytes()));

		userMapper.updatePassword(user);

	}
}
